  <template>
  <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
    <div class="favorites">
      <a-space direction="horizontal" :size="16" style="margin-bottom: 16px;">
        <span>用户名</span>
        <a-select
            v-model:value="selectedUserId"
            placeholder="选择用户名"
            style="width: 200px;"
        >
          <a-select-option value="">全部</a-select-option>
          <a-select-option v-for="user in userOptions" :key="user.value" :value="user.value">
            {{ user.label }}
          </a-select-option>
        </a-select>
        <a-button type="primary" @click="handleFilter">检索</a-button>
        <a-button @click="resetFilter">重置</a-button>
        <a-button type="primary" @click="showEditModal">
          新增
        </a-button>
      </a-space>
      <div class="table-container">
      <a-table
          :columns="columns"
          :row-key="generateRowKey"
          :data-source="favorites"
          :pagination="pagination"
          :loading="isLoading"
          @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'favoritedAt'">
            <span>{{ formatDate(record.favoritedAt) }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'username'">
            <span>{{ getUsername(record.userId) }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'jobTitle'">
            <span>{{ getJobTitle(record.jobId) }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-space size="small">

              <a-popconfirm
                  title="是否确认要删除?"
                  ok-text="Yes"
                  cancel-text="No"
                  @confirm="deleteFavorite(record)"
              >
                <a-button danger>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
      </div>
    </div>
  </a-layout-content>

  <!-- update模态框 -->
  <a-modal v-model:open="editModalOpen" title="编辑收藏" :confirm-loading="confirmLoading" @ok="handleEditOk">
    <a-form ref="editFormRef" :model="selectedFavorite" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="用户名">
        <a-select v-model:value="selectedFavorite.userId" :options="userOptions" />
      </a-form-item>
      <a-form-item label="职位名">
        <a-select v-model:value="selectedFavorite.jobId" :options="jobOptions" />
      </a-form-item>
      <a-form-item label="收藏时间">
        <a-date-picker v-model:value="selectedFavorite.favoritedAt" show-time format="YYYY-MM-DD HH:mm:ss" />
      </a-form-item>
    </a-form>
  </a-modal>

</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from 'axios';
import dayjs, { Dayjs } from 'dayjs';
import { message } from 'ant-design-vue';
/* eslint-disable */
interface Favorite {
  userId: number;
  jobId: number;
  favoritedAt: string | Dayjs;
}

const favorites = ref<Favorite[]>([]);
const originalFavorites = ref<Favorite[]>([]);
const isLoading = ref<boolean>(true);
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  position: 'bottom'
});
const selectedUserId = ref<number | ''>('');

// 用户和职位选项
const userOptions = ref<{ value: number; label: string }[]>([]);

// 编辑弹窗相关
const editModalOpen = ref<boolean>(false);
const selectedFavorite = ref<Favorite>({
  userId: 0,
  jobId: 0,
  favoritedAt: dayjs().toISOString()
});
const confirmLoading = ref<boolean>(false);
const editFormRef = ref();




const columns = [
  { title: '用户名', dataIndex: 'username' },
  { title: '职位名', dataIndex: 'jobTitle' },
  { title: '收藏时间', dataIndex: 'favoritedAt' },
  { title: '操作', dataIndex: 'action' }
];

const formatDate = (date: string | Dayjs): string => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

// 获取用户名
const getUsername = (userId: number): string => {
  const user = userOptions.value.find(user => user.value === userId);
  return user ? user.label : '未知用户';
};

// 获取职位名
const getJobTitle = (jobId: number): string => {
  const job = jobOptions.value.find(job => job.value === jobId);
  return job ? job.label : '未知职位';
};

// 获取用户选项
const fetchUserOptions = async () => {
  try {
    const res = await axios.get('/users/list', {
      params: {
        page: 1,
        size: 100
      }
    });
    userOptions.value = res.data.data.list.map((user: any) => ({
      value: user.userId,
      label: user.username
    }));
  } catch (err) {
    console.error('获取用户列表失败:', err);
    message.error('获取用户列表失败');
  }
};

const fetchFavorites = async () => {
  try {
    isLoading.value = true;
    const res = await axios.get('/favorites/list', {
      params: {
        page: pagination.value.current,
        size: pagination.value.pageSize
      }
    });
    isLoading.value = false;
    pagination.value.total = res.data.data.total;
    favorites.value = res.data.data.list;
    originalFavorites.value = [...res.data.data.list];
  } catch (err) {
    console.error('请求失败:', err);
    isLoading.value = false;
  }
};

const handleTableChange = (pag: any) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
  if (!isSearch.value) {
    fetchFavorites();
  } else {
    handleSearch();
  }
};

const isSearch = ref<boolean>(false);

const handleSearch = async () => {
  try {
    isLoading.value = true;
    const res = await axios.post('/favorites/query', {
      userId: selectedUserId.value
    });
    isSearch.value = true;
    pagination.value.total = res.data.data.length;
    favorites.value = res.data.data;
    isLoading.value = false;
  } catch (err) {
    console.error('搜索失败:', err);
    isLoading.value = false;
  }
};


const showEditModal = (record: Favorite) => {
  selectedFavorite.value = {
    userId: record.userId,
    jobId: record.jobId,
    favoritedAt: dayjs(record.favoritedAt)
  };
  editModalOpen.value = true;
};

const handleEditOk = async () => {
  confirmLoading.value = true;
  try {
    await axios.post('/favorites/update', {
      userId: selectedFavorite.value.userId,
      jobId: selectedFavorite.value.jobId,
      favoritedAt: formatDate(selectedFavorite.value.favoritedAt)
    }).then(res => {
      if (res.data.code === 200) {
        message.success("添加成功");
        editModalOpen.value = false;
        fetchFavorites();
      } else {
        message.error(res.data.message);
      }
    });
    editModalOpen.value = false;
    //刷新页面
    fetchFavorites();
    fetchUserOptions();
    fetchJobOptions();
  } catch (err) {
    message.error('更新失败，请重试');
  } finally {
    confirmLoading.value = false;
  }
};



const deleteFavorite = async (record: Favorite) => {
  try {
    await axios.post('/favorites/delete', {
      userId: record.userId,
      jobId: record.jobId
    });
    message.success('删除成功');
    fetchFavorites();
    fetchUserOptions();
    fetchJobOptions();
  } catch (err) {
    message.error('删除失败，请重试');
  }
};

// 生成唯一的行键
const generateRowKey = (record: Favorite): string => {
  return `${record.userId}-${record.jobId}`;
};

const jobOptions = ref<{ value: number; label: string }[]>([]);

const fetchJobOptions = async () => {
  try {
    const res = await axios.get('/jobs/list', {
      params: {
        page: 1,
        size: 100
      }
    });
    jobOptions.value = res.data.data.list.map((job: any) => ({
      value: job.jobId,
      label: job.title
    }));
  } catch (err) {
    console.error('获取职位列表失败:', err);
    message.error('获取职位列表失败');
  }
};

// 初始化时加载用户和职位选项
onMounted(async () => {
  await fetchUserOptions();
  await fetchJobOptions();
  await fetchFavorites();
});

// 筛选方法
const handleFilter = () => {
  isLoading.value = true;
  axios.post('/favorites/query', {
    userId: selectedUserId.value || undefined,
  }).then(res => {
    if (res.data.code === 200) {
      isSearch.value = true;
      pagination.value.total = res.data.data.length;
      favorites.value = res.data.data;
      isLoading.value = false;
      message.success('筛选成功');
    } else {
      message.error('筛选失败');
    }
  }).catch(() => {
    message.error('筛选失败，请稍后重试');
    isLoading.value = false;
  });
};

// 重置筛选方法
const resetFilter = () => {
  selectedUserId.value = '';
  fetchFavorites();
};

</script>

<style scoped>
/* 关键样式 */
.table-container {
  position: relative;
  height: 600px;  /* 固定容器高度 */
}

/* 强制分页定位到底部 */
:deep(.ant-pagination) {
  position: sticky;
  bottom: 0;
  width: 100%;
  background: white;
  padding: 16px;
  z-index: 1;
}

/* 表格内容区域高度自适应（避免被分页遮挡） */
:deep(.ant-table-body) {
  max-height: calc(100% - 64px) !important;  /* 根据分页高度调整 */
  overflow-y: auto !important;
}
</style>
